package com.weavernorth.salestasks;




import weaver.conn.RecordSet;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import java.util.Calendar;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import sun.misc.BASE64Encoder;
import weaver.general.BaseBean;
import weaver.general.Util;
import java.io.IOException;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import java.util.Iterator;
public class SalesTasksAction  implements Action  {


    public static Log log = LogFactory.getLog(SalesTasksAction.class.getName());
    //sendPost
    public String sendPost(String strUrl, String strRequestXml, String strEncoding) throws IOException {
        //基础类
        BaseBean bb = new BaseBean();

        String strBody = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();

        //创建post方式请求对象
        try {
            HttpPost httpPost = new HttpPost(strUrl);

            //装填参数
            StringEntity stringEntity = new StringEntity(strRequestXml, "utf-8");
            //log.info("请求xml=" + strRequestXml);
            //设置参数到请求对象中
            httpPost.setEntity(stringEntity);
            log.info("请求地址=" + strUrl);
            //获取用户名
            String strUsername = Util.null2String(bb.getPropValue("salestasks-erdos", "username"));
            //获取密码
            String strPassword = Util.null2String(bb.getPropValue("salestasks-erdos", "password"));
            //sap的接口需验证
            String strValue = "Basic " + (new BASE64Encoder().encode((strUsername + ":" + strPassword).getBytes()));
            httpPost.setHeader("Authorization", strValue);
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");

            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                strBody = EntityUtils.toString(entity, strEncoding);
                // log.info("返回结果=" + strBody);
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (Exception e) {
            log.info("异常捕获=" + e);
        }
        return strBody;
    }





    @Override
    public String execute(RequestInfo requestInfo) {
        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();

        boolean isSuccess = false;
        //获取当前日期
        Calendar now = Calendar.getInstance();
        int day=now.get(Calendar.DAY_OF_MONTH);
        String requestid = requestInfo.getRequestid();//请求ID
        String workflowid = requestInfo.getWorkflowid();//流程ID
        String tablename = requestInfo.getRequestManager().getBillTableName();//表单名称
        bb.writeLog("销售任务tablename的值是:" + tablename +"\n requestid"+requestid);



        RecordSet mbrs = new RecordSet();//码表rs
        String mbsql="";  //查询码表sql

        //1.获取主表单数据
        String sql = " select * from " + tablename + " where requestid =" + requestid;
        bb.writeLog("销售任务sql的值是:" + sql +"\n");
        rs.execute(sql);




        //2.封装sap请求xml
        StringBuffer  xml=new StringBuffer("");


        xml.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:sap-com:document:sap:rfc:functions\">");


        xml.append("<soapenv:Header/>");
        xml.append("<soapenv:Body>");
        xml.append("<urn:ZF_IF213_SALES_TASK>");
        xml.append("<I_MSGID></I_MSGID>");
        xml.append("<I_SENDR></I_SENDR>");
        xml.append("<T_TABLE>");

        int  years=0;
        int  months=0;

        //取主表信息

        if(rs.next()) {

            years =rs.getInt("nf") ;           //年
            months =rs.getInt("yf")  + 1;;     //月

            bb.writeLog("销售任务字段:year:" + years +"\n");
            bb.writeLog("销售任务字段:month:" + months +"\n");
        }


     //获取子表
        //===========子表= _dt1===================

        RecordSet dt1rs = new RecordSet();

        //1.获取子表单dt1数据
        String dt1sql = " select  * from " + tablename +"_dt1 dt1 "+ " where dt1.mainid=( select id from " + tablename+ " mt where mt.requestid =" + requestid +")";

        bb.writeLog("销售任务dt1sql的值是:" + dt1sql +"\n");
        dt1rs.execute(dt1sql);





        while(dt1rs.next()) {

            xml.append("<item>");

            String dpbh= dt1rs.getString("dpbh");
            Double xse= dt1rs.getDouble("xsrwe");


            bb.writeLog("销售任务字段:dpbh:" + dpbh +"\n");
            bb.writeLog("销售任务字段:xse:" + xse +"\n");



            xml.append("<KUNNR>"+dpbh+"</KUNNR>"); //店铺编号
            xml.append("<ZYEAR>"+ years +"</ZYEAR>");//年
            xml.append("<ZMONTH>"+ months +"</ZMONTH>");//月
            xml.append("<WAERS></WAERS>");
            xml.append("<ZAMOUT><![CDATA["+xse+"]]></ZAMOUT>");//销售额

            xml.append("<NOTE1></NOTE1>");
            xml.append("<NOTE2></NOTE2>");
            xml.append("<NOTE3></NOTE3>");
            xml.append("<NOTE4></NOTE4>");
            xml.append("<NOTE5></NOTE5>");
            xml.append("<NOTE6></NOTE6>");
            xml.append("<NOTE7></NOTE7>");
            xml.append("<NOTE8></NOTE8>");
            xml.append("<NOTE9></NOTE9>");
            xml.append("<NOTE10></NOTE10>");
            xml.append("<NOTE11></NOTE11>");
            xml.append("<NOTE12></NOTE12>");
            xml.append("<NOTE13></NOTE13>");
            xml.append("<NOTE14></NOTE14>");
            xml.append("<NOTE15></NOTE15>");
            xml.append("</item>");
        }
        //*************************************
        xml.append("</T_TABLE>");
        xml.append("</urn:ZF_IF213_SALES_TASK>");
        xml.append("</soapenv:Body>");
        xml.append("</soapenv:Envelope>");
        bb.writeLog("销售任务XML的值是:" + xml.toString());
        //推送数据
        //CommonToSapUtil commonToSapUtil=new CommonToSapUtil();
        try {
            //3.推送数据
            String xsrwurl = Util.null2String(bb.getPropValue("salestasks-erdos", "xsrwurl"));
            bb.writeLog("销售任务URL的值是:" + xsrwurl.toString());
            String responseXml=   sendPost(xsrwurl, xml.toString(), "utf-8");
            bb.writeLog("销售任务SAP返回的值是:" + responseXml.toString());

            //===========SAP 返回解析====================



            //xmlStr为上图格式的字符串


            //String returnString="";//返回字符串

            Document doc = null;
            try {
                doc = DocumentHelper.parseText(responseXml.toString());
                Iterator<Element> its2= doc.selectNodes("//IFFLG").iterator();
                while (its2.hasNext()){
                    Element element=its2.next();
                    String testType=element.getText();
                    //System.out.println(testType);




                    if(testType.equals("S") ){

                        isSuccess = true;
                        bb.writeLog("testType值为:" + testType +"\n");

                        break;
                    }

                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }





        }catch (Exception e){
            e.printStackTrace();

        }





        //返回状态
        if(isSuccess == false) {

            //失败
            bb.writeLog("销售任务上传失败\n");
            return FAILURE_AND_CONTINUE;

        }

        bb.writeLog("销售任务上传成功\n");
        return SUCCESS;
    }
}